from flask import Flask, request, jsonify, render_template
from flask_mysqldb import MySQL
import requests

app = Flask(__name__)

@app.route('/')
def index():
    return '''
    <html><body>
    <h1>Music Search and Download</h1>
    <form action="/search_and_download" method="get">
        <input type="text" name="key" placeholder="Enter artist name" required>
        <input type="text" name="total_pages" placeholder="Number of pages (default: 1)" value="1">
        <button type="submit">Search and Prepare Downloads</button>
    </form>
    </body></html>
    '''

# 配置 MySQL 连接参数
app.config['MYSQL_HOST'] = 'localhost'  # 或者你的实际数据库主机名
app.config['MYSQL_PORT'] = 3306
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'wanglibo123..'
app.config['MYSQL_DB'] = 'Song'
mysql = MySQL(app)

@app.route('/search_and_download', methods=['GET'])
def search_and_download():
    key = request.args.get('key', '')
    total_pages = int(request.args.get('total_pages', '1'))
    pageSize = request.args.get('pageSize', '20')
    t = request.args.get('t', '0')

    for pageNo in range(1, total_pages + 1):
        api_url = f"http://127.0.0.1:3300/search?key={key}&pageNo={pageNo}&pageSize={pageSize}&t={t}"
        try:
            response = requests.get(api_url)
            response.raise_for_status()
            data = response.json()
            songs = data.get('data', {}).get('list', [])
            for song in songs:
                songmid = song.get('songmid', '')
                if songmid:
                    # Get the actual download URL
                    actual_download_link = get_actual_download_url(songmid)
                    if actual_download_link:
                        song_data = {
                            'songname': song.get('songname', ''),
                            'albumname': song.get('albumname', ''),
                            'singer': ', '.join([singer.get('name', '') for singer in song.get('singer', [])]),
                            'songmid': songmid,
                            'download_link': actual_download_link
                        }

                        # Insert song data into database if not already present
                        cursor = mysql.connection.cursor()
                        cursor.execute("SELECT songmid FROM Songs WHERE songmid = %s", (songmid,))
                        result = cursor.fetchone()
                        if not result:
                            sql = """INSERT INTO Songs (songname, albumname, singer, songmid, download_link)
                                     VALUES (%s, %s, %s, %s, %s)"""
                            cursor.execute(sql, (song_data['songname'], song_data['albumname'], song_data['singer'], song_data['songmid'], song_data['download_link']))
                            mysql.connection.commit()
                        cursor.close()
        except requests.exceptions.RequestException as e:
            return jsonify({'error': str(e), 'message': 'Failed to fetch data from API'}), 500

    return jsonify({'message': 'Data fetched and stored successfully'})





@app.route('/play/<song_id>')
def play_song(song_id):
    music_url = get_music_urls(song_id)
    return jsonify(music_url)

@app.route('/download/<song_id>')
def download_song(song_id):
    download_url = get_actual_download_url(song_id)
    return jsonify(download_url)

def get_music_urls(song_ids):
    url = "http://127.0.0.1:3300/song/urls"
    params = {"id": song_ids}
    response = requests.get(url, params=params)
    if response.status_code == 200:
        data = response.json()
        if data["result"] == 100:
            return data["data"]
        else:
            return {'error': 'Failed to get music URLs', 'details': data}
    else:
        return {'error': 'Failed to fetch data', 'status_code': response.status_code}

def get_actual_download_url(song_id):
    url = f"http://127.0.0.1:3300/song/url?id={song_id}"
    try:
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            if data['result'] == 100 and 'data' in data:
                return data['data']  # Assume 'data' contains the actual download URL
    except requests.RequestException as e:
        print(f"Error fetching download URL: {e}")
    return None


if __name__ == '__main__':
    app.run(debug=True)
